from flask import Flask, request, jsonify, render_template
import pandas as pd
import joblib
import numpy as np
from sklearn.linear_model import LinearRegression

app = Flask(__name__)

uploaded_data = None
model = LinearRegression()

@app.route('/upload', methods=['POST'])
def upload_file():
    global uploaded_data
    if 'file' not in request.files:
        return jsonify({"error": "没有上传文件"}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "没有选择文件"}), 400
    if file and file.filename.endswith('.xlsx'):
        try:
            uploaded_data = pd.read_excel(file)
            if 'Voltage' not in uploaded_data.columns or 'Distance' not in uploaded_data.columns:
                return jsonify({"error": "Excel 文件中没有找到 'Voltage' 或 'Distance' 列"}), 400
            voltages = uploaded_data['Voltage'].tolist()
            distances = uploaded_data['Distance'].tolist()

            X = np.array(voltages).reshape(-1, 1)
            y = np.array(distances)
            model.fit(X, y)
            slope = model.coef_[0]
            intercept = model.intercept_

            return jsonify({
                "message": "文件上传成功",
                "voltages": voltages,
                "distances": distances,
                "slope": slope,
                "intercept": intercept
            })
        except Exception as e:
            return jsonify({"error": str(e)}), 500
    else:
        return jsonify({"error": "只支持上传 .xlsx 文件"}), 400

@app.route('/predict', methods=['POST'])
def predict():
    global uploaded_data
    if uploaded_data is None:
        return jsonify({"error": "请先上传 Excel 文件"}), 400

    data = request.get_json()
    voltage = data.get('voltage')
    try:
        voltage = float(voltage)
        X = uploaded_data[['Voltage']]
        y = uploaded_data['Distance']
        model.fit(X, y)
        predicted_distance = model.predict([[voltage]])[0]
        return jsonify({"distance": f"{predicted_distance:.2f}"})
    except ValueError:
        return jsonify({"error": "请输入有效的电压值！"}), 400

@app.route('/calculate_b_field', methods=['POST'])
def calculate_b_field():
    global uploaded_data
    if uploaded_data is None:
        return jsonify({"error": "请先上传 Excel 文件"}), 400

    data = request.get_json()
    kh = data.get('kh')
    current = data.get('current')

    try:
        kh = float(kh)
        current = float(current)
        if kh == 0 or current == 0:
            raise ValueError
    except ValueError:
        return jsonify({"error": "请输入有效的霍尔灵敏度 KH 和激励电流 I"}), 400

    voltages = uploaded_data['Voltage'].tolist()
    b_fields = [V / (kh * current) for V in voltages]

    return jsonify({
        "voltages": voltages,
        "bFields": b_fields
    })

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == "__main__":
    app.run(debug=True)